/**
 *
 */
$(function(){
    $(document).keyup(function (e) {
        if(e.which==13){
            $('#selectBtnEnter').click();
        }
    })
});
var path = '../';
var pageListUrl = path + 'postion/equipmentPictureDetail';
var pageUrl = path + 'postion/';

//添加弹窗
var addPanel = null;
var addPanelPicture = null;
var equipmentCode="";
// ---------------交互代码begin-----------------
//本页面业务逻辑
var postion = {
    checkLogic: function (dataObj) {
        var result = "";
        var isSubmit = true;
        //TODO 逻辑校验，去掉不必要的:
        //检查表单是否存在错误
        $.each(dataObj, function (key) {
            if (key.indexOf('Err') != -1 && dataObj[key].length > 0) {
                return false;
            }
        });
        return isSubmit;
    },
    checkFileType: function () {
        var fileName = $("#file")[0].files[0].name;
        var fileType = fileName.substr(fileName.lastIndexOf(".") + 1, fileName.length);
        if (fileType.toUpperCase() != 'XLSX' && fileType.toUpperCase() != 'XLS') {
            importVue.fileErr = "请选择*.xlsx或者*.xls格式的Excel文件";
            return false;
        }
        return true;
    }
};
//本页面业务逻辑
var advInfo={
    checkLogic:function(dataObj,err,fg){
        advInfo.clear(err);
        console.log(dataObj)
        var result="";
        var isSubmit=true;
        //TODO 逻辑校验，去掉不必要的:
        result=customUtils.checkLen(dataObj.postionCode,1,32,'位置编号');
        if(result.length!=0){
            err.positionCodeErr=result;
            isSubmit=false;
        }
        $.ajax({
            url : pageUrl + "checkPositionCode",
            type : "POST",
            dataType: "json",
            data : {postionCode:dataObj.postionCode},
            cache:false ,
            async: false
        }).done(function(res) {
            if(res.result=='0'){
                err.positionCodeErr='位置编号不存在';
                isSubmit=false;
            }
        })
        var topImg = $("#topImg")[0].files[0];
        //文件空校验
        if(!topImg){
            err.topImgErr = "请上传广告资源";
            isSubmit = false;
        }

        //文件格式校验
        var imgType = ["jpg","png","gif","jpeg","bmp"];
        var videoType = ["mp4","avi","mov","asf","wmv","rm"];
        var musicType = ["mp3"];
        // if(topImg && bottomImg && middleVideo){
        if(topImg){
            var type = topImg.name.substr(topImg.name.lastIndexOf(".") + 1,topImg.name.length).toLowerCase();
            if($.inArray(type,imgType) == '-1'){
                err.topImgErr = "请上传" + imgType.toString() + "格式的图片";
                isSubmit = false;
            }
        }
        console.log(err)
        //检查表单是否存在错误
        $.each(err, function(key) {
            if(key.indexOf('Err')!=-1 && err[key].length>0){
                return false;
            }
        });
        return isSubmit;
    },
    clear:function(obj){
        $.each(obj,function (key) {
            if($.isArray(obj[key])){
                obj[key] = [];
            }else{
                obj[key] = "";
            }
        });
    }
};
//绑定列表List---begin----所有的操作都围绕列表展开，新增、更新其他比较独立 
var dataList = new Vue({
    el: "#postionList",
    data: {
        pageInfo: {},
        pageInfo1: {},
        pageInfo2: {},
        //TODO 自定义条件查询---begin--------
        condition: {
            page: 1,
            rows: customUtils.pageSize,

            items: [],
            all: false,
            key: "",
            equipmentCode:"",
            pictureType:"",
            param1:"",
            param2:"",
            province: "",
            city: "",
            area: "",
            statusOk: "",
            statusNo: "",
            Percentage: "",


            provinces: [],
            citys: [],
            areas: [],


            id: "",
            postionCode: "",
            shopCode: "",
            companyName: "",
            shopName: "",
            shopContacts: "",
            shopPhone: "",
            empno: "",

            address: "",
            createdBy: "",
            createdDate: "",
            updatedBy: "",
            updatedDate: "",
            installPhoto: "",
            installDate: "",
            flowRate:"",
            status: "",
            overDate:"",
            startDate:""
        },
        equipmentCode:"",
        //自定义条件查询---end--------
        selectIds: [],//多选
        showSuccess: false,//false不显示成功提示
        selectedIdx: -1,//保存操作行的索引
        isSearch: false,//init:页面初始化；search:点击查询；paging:点击翻页；changePageSize:改变页面显示条数
        selectedPageSize: customUtils.pageSize//修改页面数据显示条数
    },
    mounted: function () {
        //初始化页面数据
        //this.getAreaData();
        this.manyValues();
        this.getList('search',equipmentCode);
        //this.getStatus();
    },
    // 在 `methods` 对象中定义方法,如果操作中函数的逻辑比较复杂，必须封装到dictType对象
    methods: {
        changeTime: function (elem) {
            addOrUpdate[elem.split('-')[0]] = $("#" + elem).val();
        },
        manyValues:function (){
            var self =this;
            var url=window.location.search;
            if(url.indexOf("?")!=-1){
                var str = url.substr(1);
                strs = str.split("&");
                var key=new Array(strs.length);
                var value=new Array(strs.length);
                for(i=0;i<strs.length;i++){
                    key[i]=strs[i].split("=")[0]
                    value[i]=unescape(strs[i].split("=")[1]);
                    if(key[i] == "equipmentCode"){
                        equipmentCode = value[i];
                        this.equipmentCode=equipmentCode;
                        //alert(equipmentCode);
                    }
                }
            }
        },
        selectChkBtn: function (e) {//用于多选事件
            this.selectIds.push($(e.target).val());
        },
        changeTime:function(elem){
            dataList.$data.condition[elem.split('-')[0]] = $("#"+elem).val();
            console.log(dataList.$data.condition);
        },
        getAreaData: function () {
            this.$http.get("../appInfo/queryAreaTree").then(function (response) {
                console.log(response)
                dataList.$data.condition.provinces = response.body;
                console.log(dataList.$data)
            }, function (res) {

            });
        },
        setCitys: function () {
            dataList.$data.condition.citys = dataList.$data.condition.province.citys;
            dataList.$data.condition.city = "";
            dataList.$data.condition.area = "";
        },
        setAreas: function () {
            dataList.$data.condition.areas = dataList.$data.condition.city.areas;
            dataList.$data.condition.area = "";
        },
        exportCustomerFlowTotal: function () {
            var self=this;
            var equipmentCode = self.condition["equipmentCode"];
            if(equipmentCode.length>0){
                var startDate = self.condition["startDate"];
                var overDate = self.condition["overDate"];
                var param2 = "customer_flow_total";
                location.href=pageUrl+"exportCustomerFlowTotal?equipmentCode="+equipmentCode+"&startDate="+startDate+"&startDate="+startDate+"&overDate="+overDate+"&param2="+param2;
            }else{
                alert("请输入设备编号");
                return;
            }
        },

        //搜索、分页列表
        getList: function (eventSrc) {
            var self = this;
            //改变页面显示条数
            if (eventSrc == "changePageSize") {
                if (this.pageInfo.pageSize != this.selectedPageSize) {
                    this.pageInfo.pageSize = this.selectedPageSize;
                    $('#pagination').jqPaginator('destroy');
                    eventSrc = 'init';//重新绘制控件
                } else {
                    return;
                }
            }
            var param = {"page": 1, "rows": customUtils.pageSize};

            //初始化时无当前页数，后台有默认第1页，每页10条
            if (this.pageInfo != undefined && this.pageInfo.pageNum != undefined) {
                self.condition["page"] = this.pageInfo.pageNum;
                self.condition["rows"] = this.pageInfo.pageSize;
            }
            param["page"] = self.condition["page"];
            param["rows"] = self.condition["rows"];
            param["startDate"] = self.condition["startDate"];
            param["overDate"] = self.condition["overDate"];
            param["pictureType"] = self.condition["pictureType"];
            param["equipmentCode"] = equipmentCode;
            this.condition.items = [];
            console.log(param)

            //发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
            customUtils.post(self, pageListUrl, param, function (response, isSuccess) {
                if (isSuccess == false) {
                    dataList.pageInfo.pages = 0;
                    customUtils.noData('无数据', 0);
                    return;
                }
                dataList.pageInfo = response.body.pagination;
                dataList.pageInfo1 = response.body.list1;
                customUtils.noData('无数据', dataList.pageInfo.pages);
                //页面初始化、搜索时，才需要执行分页控件
                if (eventSrc == 'init' || eventSrc == 'search') {
                    customUtils.paging('#pagination', dataList.pageInfo.pages, customUtils.showPage, function (num) {
                        //当前页码pageNum与将要翻页的页码num不相等才执行，否则为同一页
                        if (dataList.pageInfo.pageNum != num) {
                            dataList.pageInfo.pageNum = num;
                            dataList.getList('paging');
                        }
                    });
                }
            }, function (response) {
                console.log(response);
                dataList.pageInfo.pages = 0;
                customUtils.noData('无数据', 0);
            });

        },
        getStatus: function () {
            var self = this;
            var param = {};
            param["statusOk"] = self.condition["statusOk"];
            param["statusNo"] = self.condition["statusNo"];
            param["Percentage"] = self.condition["Percentage"];
            console.log(param)
            //发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
            customUtils.post(self, pageUrl + "getStatus", param, function (response, isSuccess) {

                dataList.$data.condition.statusNo = response.body.statusNo;
                dataList.$data.condition.statusOk = response.body.statusOk;
                dataList.$data.condition.Percentage = Math.round((response.body.statusOk / (response.body.statusNo + response.body.statusOk)) * 10000) / 100;
            }, function (response) {
                console.log(response)
            });
        },
        getStatusByCondition: function () {
            var self = this;
            var param = {};
            param["key"] = self.condition["key"];
            param["province"] = self.condition["province"] == '' ? "" : self.condition["province"].code;
            param["city"] = self.condition["city"] == '' ? "" : self.condition["city"].code;
            param["area"] = self.condition["area"] == '' ? "" : self.condition["area"].code;
            param["status"] = self.condition["status"];
            console.log(param)
            //发送请求,第一个参数http对象，第二个是url，第三个是参数，第四个是成功回调，第五个是请求失败回调
            customUtils.post(self, pageUrl + "getStatusByCondition", param, function (response, isSuccess) {

                dataList.$data.condition.statusNo = response.body.statusNo;
                dataList.$data.condition.statusOk = response.body.statusOk;
                dataList.$data.condition.Percentage = Math.round((response.body.statusOk / (response.body.statusNo + response.body.statusOk)) * 10000) / 100;
            }, function (response) {
                console.log(response)
            });
        },
        importPostion: function () {
            var obj3 = document.getElementById('file');
            obj3.outerHTML = obj3.outerHTML;
            $(".errMsg").html("");
            importVue.fileErr = "";
            importPanel = layer.open({
                type: 1,
                title: "导入位置信息",
                area: ['600px', '70%'],
                shadeClose: false, // 点击遮罩关闭
                content: $('#importPanel')
            });
        },
//打开添加对话框
        addOrUpdatePanelPicture:function(flag){
            var obj1 = document.getElementById('topImg') ;
            obj1.outerHTML=obj1.outerHTML;
            advInfo.clear(addOrUpdate.$data.err);
            advInfo.clear(addOrUpdate.$data.field);

            console.log(addOrUpdate.$data.field)
            if(flag != 'update'){
                addOrUpdate.$data.id="";
                addOrUpdate.$data.field.advType = '2';
                $(".t11").hide();
            }else{
                $(".t12").show();
            }
            //清除表单数据，否则会有前一条修改数据的内容
            // $.each(addOrUpdate.$data, function(key) {
            // addOrUpdate[key]="";
            // });
            var tmpTitle =  flag=="add"?"添加":"修改";
            addOrUpdate.typeChange()
            addPanelPicture = layer.open({
                type : 1,
                title :tmpTitle+"安装广告机图片上传",
                area : [ '650px', '80%' ],
                shadeClose : false, // 点击遮罩关闭
                content : $('#addPanelPicture')
            });
        },
        //更新状态
        updateStatus: function (status) {
            var size = dataList.condition.items.length;
            if (size <= 0) {
                return;
            }
            var str = status == 1 ? "有效" : "无效";
            var msg = "您确定要将" + size + " 条位置信息置为<" + str + ">状态";
            var self = this;
            layer.confirm(msg, function (index) {
                var param = {};
                param["items"] = JSON.stringify(dataList.condition.items);
                param["status"] = status;
                customUtils.post(self, pageUrl + "/updateStatus", param, function (response, isSuccess) {

                    dataList.getList('no');
                }, function (response) {
                    customUtils.showRequestTips(response, 3000)
                });
                layer.close(index);
                return true;
            });
            return false;
        },
        //初始化更新，更新对话框
        updateInit: function (index) {
            //先显示窗口，才有加载效果
            this.addOrUpdatePanel("update");
            var record = this.pageInfo.list[index];
            this.selectedIdx = index;
            var url = pageUrl + 'id/' + record.id;
            var self = this;
            customUtils.get(self.$http, url, function (response, isSuccess) {
                if (isSuccess == false) {
                    return;
                }
                //回显表单数据
                $.each(response.body, function (key) {
                    if (addOrUpdate[key] !== undefined && response.body[key]) {
                        addOrUpdate[key] = response.body[key];
                    }
                });
            }, function (response) {
                console.log(response);
            });
        },
        //全选--取消全选方法
        checkAll: function () {
            console.log(this.condition);
            if (this.condition.all) {
                this.condition.all = false;
                $("tbody").find("input[type='checkbox'][name='id']").each(function (i, val) {
                    dataList.condition.items = [];
                });
            } else {
                this.condition.all = true;
                $("tbody").find("input[type='checkbox'][name='id']").each(function (i, val) {
                    dataList.condition.items[i] = val.value;
                });
            }
        },


        //打开添加对话框
        addOrUpdatePanel: function (flag) {
            //清除表单数据，否则会有前一条修改数据的内容
            $.each(addOrUpdate.$data, function (key) {
                addOrUpdate[key] = "";
            });
            var tmpTitle = flag == "add" ? "添加" : "修改";
            addPanel = layer.open({
                type: 1,
                title: tmpTitle + "位置管理",
                area: ['570px', 'auto'],
                shadeClose: false, // 点击遮罩关闭
                content: $('#addPanel')
            });
        }
    },
    filters: {
        // 时间格式化
        timeStamps (StatusMinute) {
            if(StatusMinute==null){
                return StatusMinute = "一天未在线";
            }
            var day = parseInt(StatusMinute / 60 / 60 / 24)
            var hour = parseInt(StatusMinute / 60 / 60 % 24)
            var min = parseInt(StatusMinute / 60 % 60)
            var second = parseInt(StatusMinute / 60 % 60 % 60)
            StatusMinute = ""
            if (day > 0) {
                StatusMinute = day + "天"
            }
            if (hour > 0 && day < 1) {
                StatusMinute += hour + "小时"
            }
            if (min > 0 && day < 1) {
                StatusMinute += parseFloat(min) + "分钟"
            }
            if (second > 0 && day < 1) {
                StatusMinute += parseFloat(second) + "秒"
            }
            if(min == 0) {
                StatusMinute = "一天未在线"
            }
            return StatusMinute
        }
    }
});
//绑定列表List---end----

//新增或更新---------begin-------
var addOrUpdate = new Vue({
    el: "#addPanelPicture",
    data: {
        postionCode: "",
        shopCode: "",
        companyName: "",
        shopName: "",
        shopContacts: "",
        shopPhone: "",
        empno: "",
        address: "",
        updatedBy: "",
        updatedDate: "",
        id: "",
        //以下是错误信息
        postionCodeErr: "",
        shopCodeErr: "",
        companyNameErr: "",
        shopNameErr: "",
        shopContactsErr: "",
        shopPhoneErr: "",
        empnoErr: "",
        addressErr: "",
        updatedByErr: "",
        updatedDateErr: "",
        showSuccess: true,//显示成功提示
        field:{
            id:"",
            advCode:"",
            positionCode:"",
            advType:"3",
            maxAge:"",
            minAge:"",
            sex:"2",
            topImg:"",
            bottomImg:"",
            middleVideo:"",
            price:""
        },
        //错误信息
        err:{
            positionCodeErr:"",
            advCodeErr:"",
            advNameErr:"",
            maxAgeErr:"",
            minAgeErr:"",
            sexErr:"",
            advPathErr:"",
            topImgErr:"",
            bottomImgErr:"",
            middleVideoErr:"",
            advTypeErr:"",
            priceErr:""
        }
    },
    //当需要在数据变化时执行异步或开销较大的操作时，这个方式是最有用的
    watch: {},
    methods: {
        changeTime: function (elem) {
            addOrUpdate[elem.split('-')[0]] = $("#" + elem).val();
        },
        save: function () {
            //逻辑校验
            if (!postion.checkLogic(this.$data)) {
                return;
            }
            //没有id的时候表示新增，否则为更新
            var actionUrl = this.id == "" ? 'save' : 'update';
            var self = this;
            customUtils.post(self, pageUrl + actionUrl, self.$data, function (response, isSuccess) {
                if (actionUrl == 'update') {
                    var record = dataList.pageInfo.list[dataList.selectedIdx];
                    //更新成功，刷新列表中对应的数据
                    $.each(record, function (key) {
                        if (addOrUpdate[key] != undefined) {
                            record[key] = addOrUpdate[key];
                        }
                    });
                } else if (isSuccess) {
                    dataList.getList('init');
                }
                if (isSuccess && addPanel) layer.close(addPanel);
            }, function (res) {
                //console.log(response.body);
            });
        },
        typeChange:function () {
            var b = addOrUpdate.$data.field.advType;
            if(b ==6){
                $("#t1").hide();
                $("#t2").show();
                // $("#t_age").show();
                // $("#t_sex").show();
                // $("#tl").html("顶部图片：")
                // $("#ml").html("中部视频：")
                // $("#topImg").prop("multiple",false);
            }else{
                $("#t1").show();
                $("#t2").hide();
            }
            // if(b ==2){

            //     $("#t_age").hide();
            //     $("#t_sex").hide();
            //     $("#tl").html("前景图片：")
            //     $("#ml").html("背景音乐：")
            //     // $("#topImg").prop("multiple",true);
            // }
        },
        savePicture:function(){
            //没有id的时候表示新增，否则为更新
            var actionUrl=this.field.id=="" ? 'save' :'update';
            //逻辑校验
            if(!advInfo.checkLogic(this.$data.field,this.$data.err,actionUrl)){
                return;
            }
            var self=this;
            var formDate = new FormData($("#addPanelPicture")[0]);
            console.log(self.$data)
            customUtils.post(self,pageUrl + "savePicture",formDate,function(response,isSuccess){
                customUtils.showTips(response.body,addOrUpdate.$data.err)
                dataList.getList('init');
                if(isSuccess && addPanelPicture)layer.close(addPanelPicture);
            },function(res){
                //console.log(response.body);
            });
        },
        //清除表单数据
        reset: function () {
            $.each(addOrUpdate.$data, function (key) {
                addOrUpdate[key] = "";
            });
        },
        resetPicture: function () {
            if(addPanelPicture)layer.close(addPanelPicture);
        }
    }
});

//新增或更新---------end-------

var importVue = new Vue({
    el: "#importPanel",
    data: {
        fileErr: ""
    },
    methods: {
        importB: function () {
            var self = this;
            if (!postion.checkFileType()) {
                return;
            }
            console.log($("#importPanel"))
            console.log($("#importPanel").find("#file")[0].files)
            var formDate = new FormData($("#importPanel")[0]);
            //没选择文件时
            if ($("#importPanel").find("#file")[0].files.length <= 0) {
                $(".errMsg").html("请选择要上传的数据文件");
                return;
            }
            customUtils.post(self, pageUrl + "uploadCustomerFlowTotal", formDate, function (response) {
                console.log(response);
                customUtils.showTips(response.body, null, 2000);
                var html = "";
                if (response.body.errList != 'undefined' && response.body.errList != '' && response.body.errList != null) {
                    response.body.errList.forEach(function (value, index) {
                        html = html + value + "<br>";
                    });
                    $(".errMsg").html(html);
                } else {
                    if (importPanel) layer.close(importPanel);
                    dataList.getList('init');
                }
            }, function (response) {
                customUtils.showRequestTips(response, 3000)
            })
            console.log(formDate);
        }
    }

});
